package com.xuecheng.content.controller;

import com.xuecheng.api.content.FileManagerApi;
import com.xuecheng.common.exception.ExceptionCast;
import com.xuecheng.content.common.constant.ContentErrorCode;
import org.apache.commons.lang.RandomStringUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

/**
 * Created on 2021/04/02/20:19 周五
 *
 * @author Lantin
 */

@RestController
public class FileManagerController implements FileManagerApi {

    @Value("${file.service.url}")
    String url;
    @Value("${file.service.bucket}")
    String bucket;
    @Value("${file.service.upload.region}")
    String region;
    @Value("${cdn.domain}")
    String domain;

    public static final String UPLOAD_FILE_TOKEN_TYPE = "1";
    public static final int UPLOAD_FILE_DEADLINE = 3600;

    @Autowired
    private RestTemplate restTemplate;

    @GetMapping("common/qnUploadToken")
    public Map<String, Object> qiniuUploadToken() {

        String requestUrl = url + "/farming/generatetoken?origin=qiniu";
        Map<String, Object> map = new HashMap<>();
        map.put("tokenType", UPLOAD_FILE_TOKEN_TYPE);
        map.put("scope", bucket);
        map.put("deadline", UPLOAD_FILE_DEADLINE);
        map.put("key", UUID.randomUUID().toString() + "_" + RandomStringUtils.randomAlphanumeric(16));

        Map body = restTemplate.postForEntity(requestUrl, map, Map.class).getBody();

        if (StringUtils.isEmpty(body.get("result").toString())) {
            ExceptionCast.cast(ContentErrorCode.E_120601);
        }
        map.put("qnToken", body.get("result"));
        map.put("up_region", region);
        map.put("domain", domain);

        return map;
    }
}
